package com.cardpay.supplier;

import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cardpay.common.util.ConstantUtil;
import com.cardpay.common.util.ValidateUtil;
import com.cardpay.page.PageBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cardpay.common.log.Log;
import com.cardpay.common.util.CharacterUtil;

/**
 * Servlet implementation class SupplierServlet
 */
@WebServlet("/SupplierServlet")
public class SupplierServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static final Logger log = Log.get();

    private static final String METHOD_ADD_UI = "ADD_UI";
    private static final String METHOD_ADD = "ADD";
    private static final String METHOD_DEL = "DEL";
    private static final String METHOD_UPDATE_UI = "UPDATE_UI";
    private static final String METHOD_UPDATE = "UPDATE";
    private static final String METHOD_LIST = "LIST";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SupplierServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");

        String method=request.getParameter("method");

        log.debug("Servlet：请求参数：method={}", method);
        if (CharacterUtil.isEmpty(method)) {
            log.error("访问路径缺少method参数！");
            return;
        }
        else if (METHOD_ADD_UI.equals(method)) {
            this.addUI(request, response);
        }
        else if (METHOD_ADD.equals(method)) {
            this.add(request, response);
        }
        else if (METHOD_DEL.equals(method)) {
            this.del(request, response);
        }
        else if (METHOD_UPDATE_UI.equals(method)) {
            this.updateUI(request, response);
        }
        else if (METHOD_UPDATE.equals(method)) {
            this.update(request, response);
        }
        else if (METHOD_LIST.equals(method)) {
            this.list(request, response);
        }
        else {
            log.error("请求地址的method参数不正确！");
            return;
        }
    }

    // 添加供应商页面（准备页面上所需的数据）
    private void addUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SupplierService supplierService = new SupplierService();
        List<Supplier> supplierList = supplierService.findAll(); // 查询出添加供应商页面上所需的角色列表信息
        request.setAttribute("supplierList", supplierList);
        request.getRequestDispatcher("add.jsp").forward(request, response);
    }

    // 新增供应商信息
    private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("supplierName");
        String contact = request.getParameter("contact");
        String telephone = request.getParameter("telephone");
        String fax = request.getParameter("fax");
        String address = request.getParameter("address");
        String descriptions = request.getParameter("descriptions");

        // 数据校验
        if (!ValidateUtil.validateName(name)) {
            log.error("Servlet：数据校验失败，供应商名称不符合要求！");
            // response.sendRedirect("");
            return;
        }

        if (!CharacterUtil.isEmpty(contact) && !ValidateUtil.validateName(contact)) {
            log.error("Servlet：数据校验失败，联系人姓名不符合要求！");
            return;
        }

        if (!CharacterUtil.isEmpty(telephone) && !ValidateUtil.validateFaxNumber(telephone)) {
            log.error("Servlet：数据校验失败，电话号码不符合要求！");
            return;
        }

        if (!CharacterUtil.isEmpty(fax) && !ValidateUtil.validateFaxNumber(fax)) {
            log.error("Servlet：数据校验失败，传真号码不符合要求！");
            return;
        }

        if (!CharacterUtil.isEmpty(address) && address.length() > 140) {
            log.error("Servlet：数据校验失败，地址长度不符合要求！");
            return;
        }

        if (!CharacterUtil.isEmpty(descriptions) && descriptions.length() > 140) {
            log.error("Servlet：数据校验失败，备注长度不符合要求！");
            return;
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat(ConstantUtil.LONG_TIME_FORMAT);

        // 封装数据
        Supplier supplier = new Supplier();
        supplier.setName(name);
        supplier.setContact(contact);
        supplier.setTel(telephone);
        supplier.setFax(fax);
        supplier.setAddress(address);
        supplier.setDescriptions(descriptions);

        SupplierService supplierService = new SupplierService();
        // 新增数据
        if (supplierService.add(supplier)) {
            response.sendRedirect("SupplierServlet?method=LIST");
        }
        else {
            log.error("Serlvet：新增供应商信息失败！");
        }
    }

    // 删除供应商信息
    private void del(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        if (CharacterUtil.isEmpty(id) || !(36 == id.length())) {
            log.error("Serlvet：数据校验失败，id参数不正确，可能为空或长度不符合要求！");
            return;
        }

        SupplierService supplierService = new SupplierService();
        Supplier supplier = supplierService.find(id);

        if (null == supplier) {
            log.error("Serlvet：数据校验失败，待删除的供应商不存在！");
            return;
        }

        // 执行删除
        if (supplierService.delete(id)) {
            response.sendRedirect("SupplierServlet?method=LIST");
        }
        else {
            log.error("删除供应商信息失败！");
        }
    }

    // 查看供应商的详细信息（准备编辑供应商页面的数据）
    private void updateUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        if (CharacterUtil.isEmpty(id) || !(36 == id.length())) {
            log.error("Serlvet：数据校验失败，id参数不正确，可能为空或长度不符合要求！");
            return;
        }

        SupplierService supplierService = new SupplierService();
        Supplier supplier = supplierService.find(id); // 查询出待查看（编辑）的供应商信息

        request.setAttribute("supplier", supplier);
        request.getRequestDispatcher("update.jsp").forward(request, response);
    }

    // 更新供应商信息
    private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String contact = request.getParameter("contact");
        String telephone = request.getParameter("telephone");
        String fax = request.getParameter("fax");
        String address = request.getParameter("address");
        String descriptions = request.getParameter("descriptions");
        String parent=request.getParameter("parent");

        // 数据校验
        if (CharacterUtil.isEmpty(id) || !(36 == id.length())) {
            log.error("Serlvet：数据校验失败，id参数不正确，可能为空或长度不符合要求！");
            return;
        }

        SupplierService supplierService = new SupplierService();
        Supplier supplier=supplierService.find(id);

        if (null == supplier) {
            log.error("Servlet：数据校验失败，待更新的供应商不存在！");
            return;
        }

        // 数据校验
        if (!ValidateUtil.validateName(name)) {
            log.error("Servlet：数据校验失败，供应商名称不符合要求！");
            // response.sendRedirect("");
            return;
        }

        if (!CharacterUtil.isEmpty(contact) && !ValidateUtil.validateName(contact)) {
            log.error("Servlet：数据校验失败，联系人姓名不符合要求！");
            return;
        }

        if (!CharacterUtil.isEmpty(telephone) && !ValidateUtil.validateFaxNumber(telephone)) {
            log.error("Servlet：数据校验失败，电话号码不符合要求！");
            return;
        }

        if (!CharacterUtil.isEmpty(fax) && !ValidateUtil.validateFaxNumber(fax)) {
            log.error("Servlet：数据校验失败，传真号码不符合要求！");
            return;
        }

        if (!CharacterUtil.isEmpty(address) && address.length() > 140) {
            log.error("Servlet：数据校验失败，地址长度不符合要求！");
            return;
        }

        if (!CharacterUtil.isEmpty(descriptions) && descriptions.length() > 140) {
            log.error("Servlet：数据校验失败，备注长度不符合要求！");
            return;
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat(ConstantUtil.LONG_TIME_FORMAT);

        // 封装数据
        supplier = new Supplier();
        supplier.setId(id);
        supplier.setName(name);
        supplier.setContact(contact);
        supplier.setTel(telephone);
        supplier.setFax(fax);
        supplier.setAddress(address);
        supplier.setDescriptions(descriptions);

        // 更新数据
        if (supplierService.update(supplier)) {
            if("BILL".equals(parent)){
                response.sendRedirect("jsp/bill/BillServlet?method=LIST");
            }else {
                response.sendRedirect("SupplierServlet?method=LIST");
            }
        }
        else {
            log.error("Serlvet：修改（更改）供应商信息失败！");
        }
    }

    // 查询供应商列表
    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageNumStr = request.getParameter("pageNum"); // 当前页码
        String querySupplierName = request.getParameter("querySupplierName"); // 页面上的查询条件（根据供应商名称进行查询）

        if (null != querySupplierName) {
            // request.getParameter(...)会进行第一次解码
            // 再调用 java.net.URLDecoder.decode(String s, String enc) 方法进行第二次解码
            querySupplierName = URLDecoder.decode(querySupplierName, "UTF-8");
        }

        int pageNum = 1; // 当前页码（默认为第1页）
        if (CharacterUtil.isNumber(pageNumStr)) {
            pageNum = Integer.parseInt(pageNumStr);
        }

        SupplierService supplierService = new SupplierService();
        // 分页查询
        PageBean<Supplier> pageBean = supplierService.findPagingSuppliers(pageNum, querySupplierName);

        request.setAttribute("querySupplierName", querySupplierName); // 回显查询条件
        request.setAttribute("pageBean", pageBean);
        request.getRequestDispatcher("list.jsp").forward(request, response);
    }
}
